package com.changgou.backend.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.backend.utils.POIUtils;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.order.feign.EvaluateFeign;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.feign.OrderItemFeign;
import com.changgou.order.pojo.Evaluate;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/worder")
public class OrderController {
    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private OrderItemFeign orderItemFeign;
    @Autowired
    private EvaluateFeign evaluateFeign;

    @GetMapping("/waitsendlist")
    @ResponseBody
    public Result waitsendlist(){
        //查出已支付未发货的订单
        Map map = new HashMap();
        map.put("orderStatus","1");
        map.put("consign_status","0");
        Result result = orderFeign.findPage(map, 1, 20);
        return result;
    }

    //评价列表
    @PostMapping("/evaluChangeReturn/{flag}")
    @ResponseBody
    public Result evaluatelist(@PathVariable("flag") String flag,@RequestBody Evaluate evaluate){
        evaluate.setIsReturn(flag);
        evaluateFeign.update(evaluate,evaluate.getId());
        return new Result(true, StatusCode.OK, "查询成功");
    }

    //评价列表
    @PostMapping("/evaluatelist/{page}/{size}")
    @ResponseBody
    public Result evaluatelist(@PathVariable("page") String page ,@PathVariable("size") String size ,@RequestBody Map searchMap){
        System.out.println(JSON.toJSONString(searchMap));
        Result result = evaluateFeign.findPage(searchMap,Integer.parseInt(page), Integer.parseInt(size));
//        return new Result(true, StatusCode.OK, "查询成功", result.getData());
        return result;
    }

    @PostMapping("/exportexcel")
    @ResponseBody
    public Result exportexcel(@RequestBody Map searchMap){  //@PathVariable("filename") String filename
        String filename = (String)searchMap.get("filename");
        if (!filename.endsWith(".xls")||!filename.endsWith(".xlsx")){
            if (filename.contains(".")){
                return new Result(false, StatusCode.ERROR, "您需要选择目录");
            }else {
                filename+="order.xlsx";
            }
        }
        List<Map> list = (List<Map>)searchMap.get("list");
        System.out.println("导出数据为"+JSON.toJSONString(list));
        List<String> columes = new ArrayList<>();
        columes.add("订单号");
        columes.add("数量合计");
        columes.add("金额合计");
        columes.add("优惠金额");
        columes.add("邮费");
        columes.add("实付金额");
        columes.add("支付类型");
        columes.add("订单创建时间");
        columes.add("订单更新时间");
        columes.add("付款时间");
        columes.add("发货时间");
        columes.add("交易完成时间");
        columes.add("交易关闭时间");
        columes.add("物流名称");
        columes.add("物流单号");
        columes.add("用户名称");
        columes.add("买家留言");
        columes.add("是否评价");
        columes.add("收货人");
        columes.add("收货人手机");
        columes.add("收货人地址");
        columes.add("订单来源");
        columes.add("交易流水号");
        columes.add("订单状态");
        columes.add("支付状态");
        columes.add("发货状态");
        columes.add("是否删除");
        List<String> Listname = new ArrayList<>();
        Listname.add("id");
        Listname.add("totalNum");
        Listname.add("totalMoney");
        Listname.add("preMoney");
        Listname.add("postFee");
        Listname.add("payMoney");
        Listname.add("payType");
        Listname.add("createTime");
        Listname.add("updateTime");
        Listname.add("payTime");
        Listname.add("consignTime");
        Listname.add("endTime");
        Listname.add("closeTime");
        Listname.add("shippingName");
        Listname.add("shippingCode");
        Listname.add("username");
        Listname.add("buyerMessage");
        Listname.add("buyerRate");
        Listname.add("receiverContact");
        Listname.add("receiverMobile");
        Listname.add("receiverAddress");
        Listname.add("sourceType");
        Listname.add("transactionId");
        Listname.add("orderStatus");
        Listname.add("payStatus");
        Listname.add("consignStatus");
        Listname.add("is_delete");
        Listname.add("isDelete");
        List<Map> mapList = new ArrayList<>();
        list.forEach(mp -> {
            String id = (String) mp.get("id");
            Order order = orderFeign.findById(id).getData();
            Map map = new HashMap();
            map.put("id",order.getId());
            map.put("totalNum",order.getTotalNum());
            map.put("totalMoney",order.getTotalMoney());
            map.put("preMoney",order.getPayMoney());
            map.put("postFee",order.getPostFee());
            map.put("payMoney",order.getPayMoney());
            if ("1".equals(order.getPayType())){
                map.put("payType","在线支付");
            }else {
                map.put("payType","货到付款");
            }
            map.put("createTime",order.getCreateTime());
            map.put("updateTime",order.getUpdateTime());
            map.put("payTime",order.getPayTime());
            map.put("consignTime",order.getConsignTime());
            map.put("endTime",order.getEndTime());
            map.put("closeTime",order.getCloseTime());
            map.put("shippingName",order.getShippingName());
            map.put("shippingCode",order.getShippingCode());
            map.put("username",order.getUsername());
            map.put("buyerMessage",order.getBuyerMessage());
            if ("0".equals(order.getBuyerRate())) {
                map.put("buyerRate","已评价");
            }else {
                map.put("buyerRate","未评价");
            }
            map.put("receiverContact",order.getReceiverContact());
            map.put("receiverMobile",order.getReceiverMobile());
            map.put("receiverAddress",order.getReceiverAddress());
            if ("1".equals(order.getSourceType())){
                map.put("sourceType","web");
            }else if ("2".equals(order.getSourceType())){
                map.put("sourceType","app");
            }else if ("3".equals(order.getSourceType())){
                map.put("sourceType","微信公众号");
            }else if ("4".equals(order.getSourceType())){
                map.put("sourceType","微信小程序");
            }else{
                map.put("sourceType","H5手机页面");
            }
            map.put("transactionId",order.getTransactionId());
            if ("0".equals(order.getOrderStatus())){
                map.put("orderStatus","未支付");
            }else if ("1".equals(order.getOrderStatus())){
                map.put("orderStatus","已支付");
            }else if ("2".equals(order.getOrderStatus())){
                map.put("orderStatus","已发货");
            }else{
                map.put("orderStatus","已完成");
            }
            if ("0".equals(order.getPayStatus())){
                map.put("payStatus","未支付");
            }else {
                map.put("payStatus","已支付");
            }
            if ("0".equals(order.getConsignStatus())){
                map.put("consignStatus","未发货");
            }else if ("1".equals(order.getConsignStatus())){
                map.put("consignStatus","已发货");
            }else {
                map.put("consignStatus","已送达");
            }
            map.put("isDelete",order.getIsDelete());
            mapList.add(map);
        });
        System.out.println(filename);
        //poi输入
        POIUtils.writeExcel(filename,mapList,columes,Listname);
        return new Result(true, StatusCode.OK, "导出excel成功");
    }

    @GetMapping("/closeOrder")
    public Result closeOrder(@RequestParam String orderId){
        orderFeign.closeOrder(orderId);
        return new Result(true, StatusCode.OK, "查询成功");
    }

    @PostMapping("/sendgoods")
    public Result sendGoods(@RequestBody Order order){
        List<Order> list = new ArrayList<>();
        list.add(order);
        orderFeign.batchSend(list);
        return new Result(true, StatusCode.OK, "订单发货成功");
    }

    @GetMapping("/findByid")
    public Result findByid(@PathVariable("id") String id){
        Order order = orderFeign.findById(id).getData();
        Result<List<OrderItem>> orderitems = orderItemFeign.findByOrderId(id);
        order.setOrderItemList(orderitems.getData());
        return new Result(true, StatusCode.OK, "查询成功",order);
    }

    @DeleteMapping("/deletByid/{id}")
    @ResponseBody
    public Result deletOrder(@PathVariable("id") String id){
        Result<List<OrderItem>> result = orderItemFeign.findByOrderId(id);
        result.getData().forEach(orderItem -> {
            orderItemFeign.delete(orderItem.getId());
        });
        orderFeign.delete(id);
        return new Result(true, StatusCode.OK, "删除订单成功");
    }

    @GetMapping("/orderItem")
    @ResponseBody
    public Result printorders(String[] orderIds){
        List orderlist = new ArrayList();
        for (String orderId : orderIds) {
            Order order = orderFeign.findById(orderId).getData();
            List<OrderItem> orderItemList = orderItemFeign.findByOrderId(orderId).getData();
            //System.out.println("远程调用订单详情"+orderItemList.size());
            order.setOrderItemList(orderItemList);
            orderlist.add(order);
        }
        return new Result(true, StatusCode.OK, "查询成功", orderlist);
    }

    @GetMapping("/toorderItempage")
    public String toprintPage(String[] orderIds,Model model){
        List orderlist = new ArrayList();
        for (String orderId : orderIds) {
            Order order = orderFeign.findById(orderId).getData();
            List<OrderItem> orderItemList = orderItemFeign.findByOrderId(orderId).getData();
            order.setOrderItemList(orderItemList);
            orderlist.add(order);
        }
        model.addAttribute("list",orderlist);
        return "orderItemsprint";
    }

    @PostMapping("/orderlist/{page}/{size}")
    @ResponseBody
    public Result list(@PathVariable("page") String page ,@PathVariable("size") String size ,@RequestBody Map searchMap){
        System.out.println(page);
        System.out.println(size);
        System.out.println(JSON.toJSONString(searchMap));
        String username = (String) searchMap.get("username");
        /*try {
            int phone = Integer.parseInt(username);
            searchMap.remove("username");
            searchMap.put("receiverMobile",phone);
        } catch (NumberFormatException e) {
            System.out.println("输入为用户名");
        }*/
        Result result = orderFeign.findPage(searchMap,Integer.parseInt(page), Integer.parseInt(size));
        return new Result(true, StatusCode.OK, "查询成功", result.getData());
    }


    @RequestMapping("/toorderpage")
    public String topage(){
        return "orderlist";
    }
    @RequestMapping("/toevaluatepage")
    public String toevaluatepage(){
        return "orderevaluetes";
    }
    @RequestMapping("/tosendlistpage")
    public String tosendlistpage(){
        return "ordersends";
    }
}
